
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.*;
import com.rt.schedulebase.entity.DictCommonUse;
import com.rt.schedulebase.entity.DictExamQueue;
import com.rt.schedulebase.entity.ExamSyslog;
import com.rt.schedulebase.mapper.ExamSyslogMapper;
import com.rt.schedulenew.api.IExamSyslogService;
import com.rt.schedulenew.utils.base.BigDecimalUtil;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.base.LogUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.PageVO;
import com.rt.schedulenew.utils.util.DateUtil;
import com.rt.schedulenew.utils.util.JsonUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.*;

@Service
public class ExamSyslogServiceImpl extends ServiceImpl<ExamSyslogMapper, ExamSyslog> implements IExamSyslogService {

    @Autowired
    private CommonServiceImpl commonServiceImpl;
    @Autowired
    private SourceServiceImpl sourceServiceImpl;

    @Override
    public boolean insertSelective(ExamSyslog examSyslog) {
        return retBool(baseMapper.insert(examSyslog));
    }

    @Override
    public boolean deleteByPrimaryKey(String key) {
        return retBool(baseMapper.deleteById((Serializable) key));
    }

    @Override
    public boolean updateByPrimaryKeySelective(ExamSyslog examSyslog) {
        return retBool(baseMapper.updateById(examSyslog));
    }

    @Override
    public ExamSyslog selectByPrimaryKey(String key) {
        return baseMapper.selectById(key);
    }

    @Override
    public List<ExamSyslog> getList(ExamSyslogDto dto) {
        QueryWrapper<ExamSyslog> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        qw.allEq(map, false);
        List<ExamSyslog> list = baseMapper.selectList(qw);
        return list;
    }

    @Override
    public List<ExamSyslog> getListAll() {
        return baseMapper.selectList(null);
    }

    @Override
    public boolean delete(ExamSyslog examSyslog) {
        UpdateWrapper<ExamSyslog> uw = new UpdateWrapper<>();
        Map<String, Object> map = new HashMap<>();
        uw.allEq(map, false);
        return retBool(baseMapper.delete(uw));
    }

    @Override
    public boolean update(ExamSyslog examSyslog) {
        UpdateWrapper<ExamSyslog> uw = new UpdateWrapper<>();
        Map<String, Object> map = new HashMap<>();
        uw.allEq(map, false);
        return retBool(baseMapper.update(examSyslog, uw));
    }

    @Override
    public ExamSyslog getInfo(ExamSyslogDto dto) {
        QueryWrapper<ExamSyslog> qw = new QueryWrapper<>();
        Map<String, Object> map = new HashMap<>();
        qw.allEq(map, false);
        return baseMapper.selectOne(qw);
    }

    @Override
    public void insertSysLog(ExamSyslog examSyslog, DictUsersDto dictUsersDto, Object oldObj, Object newObj, String keyName) {
        StringBuilder sb = new StringBuilder();
        sb.append("【");
        sb.append(ConstantsUtil.OperateName.get(examSyslog.getOperateName()));
        sb.append("--");
        sb.append(ConstantsUtil.ModuleName.get(examSyslog.getModuleName()));
        sb.append("--");
        sb.append(keyName);
        sb.append("】");
        if (ConstantsUtil.OperateName.UPDATE.name().equals(examSyslog.getOperateName())) {
            String str = LogUtil.compareObject(oldObj, newObj);
            sb.append(str);
        }
        ExamSyslog syslog = new ExamSyslog();
        syslog.setOperateName(ConstantsUtil.OperateName.get(examSyslog.getOperateName()));
        syslog.setModuleName(examSyslog.getModuleName());
        syslog.setUserId(dictUsersDto.getUserId());
        syslog.setUserName(dictUsersDto.getName());
        syslog.setComputerName(dictUsersDto.getIpAddress());
        syslog.setPatLocalId(examSyslog.getPatLocalId());
        syslog.setOperateDate(DateUtil.getCurrDateStr());
        syslog.setOperateTime(DateUtil.getCurrentTime());
        int length = sb.length();
        double num = BigDecimalUtil.divide(length, 2000.0);
        num = (Math.max(num, 1.0));
        for (int i = 0; i < num; ++i) {
            int startIdx = i * 2000;
            int endIdx = (i + 1) * 2000;
            endIdx = (Math.min(endIdx, length));
            String desc = sb.substring(startIdx, endIdx);
            syslog.setDescription(desc);
            insertSelective(syslog);
        }
    }

    public static void main(String[] args) {
        String moduleName = ConstantsUtil.ModuleName.DICT_SCHEDULE_APM_COMMON.name();
        String operateName = ConstantsUtil.OperateName.UPDATE.name();
        DictScheduleApmDto oldObj = new DictScheduleApmDto();
        oldObj.setApmCode("123");
        oldObj.setPageNo(1);
        DictScheduleApmDto newObj = new DictScheduleApmDto();
        newObj.setApmCode("4561");
        newObj.setPageNo(2);
        ExamSyslog examSyslog = new ExamSyslog();
        examSyslog.setModuleName(moduleName);
        examSyslog.setOperateName(operateName);
    }


    @Override
    public void saveExamSyslogForDesc(String moduleName, String operateName, DictScheduleApmDto scheduleApm) {
        String desc = "";
        if (ConstantsUtil.ModuleName.DICT_SCHEDULE_REGULAR_DEF.name().equals(moduleName)) {
            desc = turnRegularDef4Desc(operateName, scheduleApm);
        } else if (moduleName.contains(ConstantsUtil.ModuleName.DICT_SCHEDULE_APM.name())) {
            desc = turnScheduleApm4Desc(operateName, scheduleApm);
        }
        saveExamSyslog(moduleName, operateName, scheduleApm.getScheduleApm(), desc);
    }

    @Override
    public void saveExamSyslog(String moduleName, String operateName, String patLocalId, String desc) {
        ExamSyslogDto examSyslogDto = new ExamSyslogDto();
        examSyslogDto.setModuleName(moduleName);
        examSyslogDto.setOperateName(operateName);
        DictUsersDto usersDto = commonServiceImpl.dictUsers(new ExamApplyDto());
        examSyslogDto.setUserId((usersDto.getUserId() == null) ? "无" : usersDto.getUserId());
        examSyslogDto.setUserName(usersDto.getName());
        examSyslogDto.setComputerName(usersDto.getIpAddress());
        examSyslogDto.setOperateDate(DateUtil.getCurrDateStr());
        examSyslogDto.setOperateTime(DateUtil.getCurrentTime());
        examSyslogDto.setPatLocalId(patLocalId);
        if (desc.length() >= 3600) {
            desc = desc.substring(0, 3580) + "......}";
        }
        examSyslogDto.setDescription(desc);
        baseMapper.insert(examSyslogDto);
    }

    private String turnScheduleApm4Desc(String operateName, DictScheduleApmDto apm) {
        String desc = "";
        if (ConstantsUtil.OperateName.UPDATE.getDesc().equals(operateName)) {
            DictScheduleApmDto oldApm = new DictScheduleApmDto();
            oldApm.setApmCode(apm.getApmCode());
            oldApm.setExamClass(apm.getExamClass());
            oldApm = sourceServiceImpl.getLastScheduleInfo(oldApm);
            desc = "【" + operateName + "---" + apm.getResourceMark() + "号源】：{ " + updateToString4Common(apm, oldApm) + " }";
            apm.setOldScheduleApm(oldApm.getScheduleApm());
        } else {
            boolean isDos = false;
            if (ConstantsUtil.OperateName.OPEN.getDesc().equals(operateName) || ConstantsUtil.OperateName.STOP.getDesc().equals(operateName)) {
                isDos = true;
            } else if (ConstantsUtil.OperateName.DELETE.getDesc().equals(operateName)) {
                apm = sourceServiceImpl.getLastScheduleInfo(apm);
            }
            desc = "【" + operateName + "---" + apm.getResourceMark() + "号源】：{ " + toString4Common(isDos, apm) + " }";
        }
        return desc;
    }

    public String toString4Common(boolean isDos, DictScheduleApmDto apm) {
        String str = "检查类别：" + apm.getExamClass() + "，预约队列名称：" + apm.getQueueName() + CommonUtil.toString4ScheduleDate(apm.getResourceMark(), apm.getScheduleDate(), apm.getWeekDate()) + "，生效日期：" + apm.getDateStart() + "~" + apm.getDateEnd() + "，停用标识：" + CommonUtil.convertStopFlag(apm.getStopFlag());
        if (!isDos) {
            str = str + (StringUtils.isNotBlank(apm.getTimeEarliest()) ? ("，最早报到时间：" + apm.getTimeEarliest()) : "") + (StringUtils.isNotBlank(apm.getTimeSignin()) ? ("，最晚报到时间：" + apm.getTimeSignin()) : "") + (StringUtils.isNotBlank(apm.getTimeScheduleLatest()) ? ("，最晚预约时间：" + apm.getTimeScheduleLatest()) : "") + (StringUtils.isNotBlank(apm.getDrugTime()) ? ("，服药时间：" + apm.getDrugTime()) : "") + "，午别：" + CommonUtil.convertApmFlag(apm.getApmFlag()) + ((apm.getMaxLimit() != null) ? (CommonUtil.toString4LimitType(apm.getLimitType()) + apm.getMaxLimit()) : "") + (StringUtils.isNotBlank(apm.getRegularDefScheduleName()) ? ("，预约规则：" + apm.getRegularDefScheduleName()) : "") + (StringUtils.isNotBlank(apm.getRegularScheduleName()) ? ("，数量规则：" + apm.getRegularScheduleName()) : "");
        }
        return str;
    }

    public String updateToString4Common(DictScheduleApmDto apm, DictScheduleApmDto oldApm) {
        String str = String.format("检查类别：" + apm.getExamClass() + "，预约队列名称：" + apm.getQueueName() + CommonUtil.toString4ScheduleDate(apm.getResourceMark(), apm.getScheduleDate(), apm.getWeekDate()) + "，生效日期：" + apm.getDateStart() + "~" + apm.getDateEnd(), new Object[0]);
        if (StringUtils.isNotBlank(apm.getApmFlag()) && !Objects.equals(oldApm.getApmFlag(), apm.getApmFlag())) {
            str = str + "，午别：【" + CommonUtil.convertApmFlag(oldApm.getApmFlag()) + "==>" + CommonUtil.convertApmFlag(apm.getApmFlag()) + "】";
        }
        if (StringUtils.isNotBlank(apm.getTimeEarliest())) {
            if (StringUtils.isNotBlank(oldApm.getTimeEarliest()) && !Objects.equals(oldApm.getTimeEarliest(), apm.getTimeEarliest())) {
                str = str + "，最早报到时间：【" + oldApm.getTimeEarliest() + "==>" + apm.getTimeEarliest() + "】";
            } else if (StringUtils.isEmpty(oldApm.getTimeEarliest()) && !StringUtils.isEmpty(apm.getTimeEarliest())) {
                str = str + "，最早报到时间：【无==>" + apm.getTimeEarliest() + "】";
            }
        }
        if (StringUtils.isNotBlank(apm.getTimeSignin()) && !Objects.equals(oldApm.getTimeSignin(), apm.getTimeSignin())) {
            str = str + "，最晚报到时间：【" + oldApm.getTimeSignin() + "==>" + apm.getTimeSignin() + "】";
        }
        if (StringUtils.isNotBlank(apm.getTimeScheduleLatest())) {
            if (StringUtils.isNotBlank(oldApm.getTimeScheduleLatest()) && !Objects.equals(apm.getTimeScheduleLatest(), oldApm.getTimeScheduleLatest())) {
                str = str + "，最晚预约时间：【" + oldApm.getTimeScheduleLatest() + "==>" + apm.getTimeScheduleLatest() + "】";
            } else if (StringUtils.isEmpty(oldApm.getTimeScheduleLatest()) && !StringUtils.isEmpty(apm.getTimeScheduleLatest())) {
                str = str + "，最晚预约时间：【无==>" + apm.getTimeScheduleLatest() + "】";
            }
        }
        if (!StringUtils.isEmpty(apm.getDrugTime())) {
            if (!StringUtils.isEmpty(oldApm.getDrugTime()) && !oldApm.getDrugTime().equals(apm.getDrugTime())) {
                str = str + "，服药时间：【" + oldApm.getDrugTime() + "==>" + apm.getDrugTime() + "】";
            } else if (StringUtils.isEmpty(oldApm.getDrugTime()) && !StringUtils.isEmpty(apm.getDrugTime())) {
                str = str + "，服药时间：【无==>" + apm.getDrugTime() + "】";
            }
        }
        if (oldApm.getMaxLimit() != null && !oldApm.getMaxLimit().equals(apm.getMaxLimit())) {
            str = str + CommonUtil.toString4LimitType(apm.getLimitType()) + "【" + oldApm.getMaxLimit() + "==>" + apm.getMaxLimit() + "】";
        } else if (oldApm.getMaxLimit() == null) {
            str = str + CommonUtil.toString4LimitType(apm.getLimitType()) + "【无 ==>" + apm.getMaxLimit() + "】";
        }
        if (!StringUtils.isEmpty(apm.getStopFlag()) && !oldApm.getStopFlag().equals(apm.getStopFlag())) {
            str = str + "，停用标识：【" + CommonUtil.convertStopFlag(oldApm.getStopFlag()) + "==>" + CommonUtil.convertStopFlag(apm.getStopFlag()) + "】";
        }
        if (oldApm.getRegularDefScheduleNameList() != null && oldApm.getRegularDefScheduleNameList().size() > 0) {
            if (!StringUtils.isEmpty(apm.getRegularDefScheduleName())) {
                List<String> bigList = oldApm.getRegularDefScheduleNameList();
                List<String> smallList = oldApm.getRegularDefScheduleNameList();
                List<String> currentList = Arrays.asList(apm.getRegularDefScheduleName().split(","));
                if (currentList.size() >= bigList.size()) {
                    bigList = currentList;
                } else {
                    smallList = currentList;
                }
                boolean isOk = false;
                for (String arr : bigList) {
                    if (!smallList.contains(arr)) {
                        isOk = true;
                        break;
                    }
                }
                if (isOk) {
                    str = str + "，预约规则：【" + String.join(",", oldApm.getRegularDefScheduleNameList()) + "==>" + apm.getRegularDefScheduleName() + "】";
                }
            } else if (StringUtils.isEmpty(apm.getRegularDefSchedule())) {
                str = str + "，预约规则：【" + String.join(",", oldApm.getRegularDefScheduleNameList()) + "==>无】";
            }
        } else if (!StringUtils.isEmpty(apm.getRegularDefScheduleName())) {
            str = str + "，预约规则：【无 ==>" + apm.getRegularDefScheduleName() + "】";
        }
        if (oldApm.getRegularScheduleNameList() != null && oldApm.getRegularScheduleNameList().size() > 0) {
            if (!StringUtils.isEmpty(apm.getRegularScheduleName())) {
                List<String> bigList = (List<String>) oldApm.getRegularScheduleNameList();
                List<String> smallList = (List<String>) oldApm.getRegularScheduleNameList();
                List<String> currentList = Arrays.asList(apm.getRegularScheduleName().split(","));
                if (currentList.size() >= bigList.size()) {
                    bigList = currentList;
                } else {
                    smallList = currentList;
                }
                boolean isOk = false;
                for (String arr : bigList) {
                    if (!smallList.contains(arr)) {
                        isOk = true;
                        break;
                    }
                }
                if (isOk) {
                    str = str + "，数量规则：【" + String.join(",", oldApm.getRegularScheduleNameList()) + "==>" + apm.getRegularScheduleName() + "】";
                }
            } else if (StringUtils.isEmpty(apm.getRegularSchedule())) {
                str = str + "，数量规则：【" + String.join(",", oldApm.getRegularScheduleNameList()) + "==>无】";
            }
        } else if (!StringUtils.isEmpty(apm.getRegularScheduleName())) {
            str = str + "，数量规则：【无 ==>" + apm.getRegularScheduleName() + "】";
        }
        return str;
    }

    private String turnRegularDef4Desc(String operateName, DictScheduleApmDto scheduleApm) {
        String desc = "[" + operateName + "预约规则]:{ [" + turn2ExcludeFlag(scheduleApm.getExcludeFlag()) + "]类别:" + scheduleApm.getExamClass() + ",规则ID:" + scheduleApm.getRegularId() + ",规则名称:" + scheduleApm.getRegularName();
        String regularContent = scheduleApm.getRegularContent();
        if (StringUtils.isNotBlank(regularContent)) {
            RuleDto ruleDto = JsonUtil.toBean(regularContent, RuleDto.class);
            if (ruleDto.getPriorityOrder() != null) {
                RuleDto.LimitScope priorityScope = ruleDto.getPriorityOrder();
                if (priorityScope.getValue().size() > 0) {
                    desc += ",优先级别:[";
                    if (StringUtils.isNotBlank(priorityScope.getGrant())) {
                        desc = desc + turn2Grant(priorityScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(priorityScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getWard() != null) {
                RuleDto.LimitScope wardScope = ruleDto.getWard();
                if (wardScope.getValue().size() > 0) {
                    desc += ",申请病区:[";
                    if (StringUtils.isNotBlank(wardScope.getGrant())) {
                        desc = desc + turn2Grant(wardScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(wardScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getDept() != null) {
                RuleDto.LimitScope deptScope = ruleDto.getDept();
                if (deptScope.getValue().size() > 0) {
                    desc += ",申请科室:[";
                    if (StringUtils.isNotBlank(deptScope.getGrant())) {
                        desc = desc + turn2Grant(deptScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(deptScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getPatientSource() != null) {
                RuleDto.LimitScope sourceScope = ruleDto.getPatientSource();
                if (sourceScope.getValue().size() > 0) {
                    desc += ",病人来源:[";
                    if (StringUtils.isNotBlank(sourceScope.getGrant())) {
                        desc = desc + turn2Grant(sourceScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join((Iterable) sourceScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getSex() != null) {
                RuleDto.LimitScope sexScope = ruleDto.getSex();
                if (sexScope.getValue().size() > 0) {
                    desc += ",病人性别:[";
                    if (StringUtils.isNotBlank(sexScope.getGrant())) {
                        desc = desc + turn2Grant(sexScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join((Iterable) sexScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getTransTool() != null) {
                RuleDto.LimitScope toolScope = ruleDto.getTransTool();
                if (toolScope.getValue().size() > 0) {
                    desc += ",运送工具:[";
                    if (StringUtils.isNotBlank(toolScope.getGrant())) {
                        desc = desc + turn2Grant(toolScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join((Iterable) toolScope.getValue(), "、") + "]";
                }
            }
            List<String> specialOnlyDoList = new ArrayList<String>();
            List<String> specialNoDoList = new ArrayList<String>();
            if (StringUtils.isNotBlank(ruleDto.getVip())) {
                if ("1".equals(ruleDto.getVip())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.VIP.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.VIP.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getClinicPath())) {
                if ("1".equals(ruleDto.getClinicPath())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CLINIC_PATH.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CLINIC_PATH.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getBedSide())) {
                if ("1".equals(ruleDto.getBedSide())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.BED_SIDE.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.BED_SIDE.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getIndolence())) {
                if ("1".equals(ruleDto.getIndolence())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.INDOLENCE.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.INDOLENCE.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCriticallyIll())) {
                if ("1".equals(ruleDto.getCriticallyIll())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CRITICALLY_ILL.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCreateDoc())) {
                if ("1".equals(ruleDto.getCreateDoc())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.CREATE_DOC.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.CREATE_DOC.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getInfectious())) {
                if ("1".equals(ruleDto.getInfectious())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.INFECTIOUS.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.INFECTIOUS.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getMultiDrug())) {
                if ("1".equals(ruleDto.getMultiDrug())) {
                    specialOnlyDoList.add(ConstantsUtil.RegularAttribute.MULTI_DRUG.getValue());
                } else {
                    specialNoDoList.add(ConstantsUtil.RegularAttribute.MULTI_DRUG.getValue());
                }
            }
            if (CollectionUtils.isNotEmpty(specialOnlyDoList)) {
                desc = desc + ",特殊属性(只做):[" + StringUtils.join(specialOnlyDoList, "、") + "]";
            }
            if (CollectionUtils.isNotEmpty(specialNoDoList)) {
                desc = desc + ",特殊属性(不做):[" + StringUtils.join(specialNoDoList, "、") + "]";
            }
            List<String> itemOnlyDoList = new ArrayList<>();
            List<String> itemNoDoList = new ArrayList<>();
            if (StringUtils.isNotBlank(ruleDto.getEnhance())) {
                if ("1".equals(ruleDto.getEnhance())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.EN_CHANCE.getValue());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.EN_CHANCE.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getCalm())) {
                if ("1".equals(ruleDto.getCalm())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.CALM.getValue());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.CALM.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getEmptyStomach())) {
                if ("1".equals(ruleDto.getEmptyStomach())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getValue());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.EMPTY_STOMACH.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getBernao())) {
                if ("1".equals(ruleDto.getBernao())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.BER_NAO.getValue());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.BER_NAO.getValue());
                }
            }
            if (StringUtils.isNotBlank(ruleDto.getPuncture())) {
                if ("1".equals(ruleDto.getPuncture())) {
                    itemOnlyDoList.add(ConstantsUtil.RegularAttribute.PUNCTURE.getValue());
                } else {
                    itemNoDoList.add(ConstantsUtil.RegularAttribute.PUNCTURE.getValue());
                }
            }
            if (CollectionUtils.isNotEmpty(itemOnlyDoList)) {
                desc = desc + ",项目属性(只做):[" + StringUtils.join(itemOnlyDoList, "、") + "]";
            }
            if (CollectionUtils.isNotEmpty(itemNoDoList)) {
                desc = desc + ",项目属性(不做):[" + StringUtils.join(itemNoDoList, "、") + "]";
            }
            if (ruleDto.getAge() != null) {
                RuleDto.AgeScope ageScope = ruleDto.getAge();
                if (CollectionUtils.isNotEmpty(ageScope.getDayScope())) {
                    desc += ",年龄约束:[";
                    if (StringUtils.isNotBlank(ageScope.getGrant())) {
                        desc = desc + turn2Grant(ageScope.getGrant()) + "=>";
                    }
                    List<String> ageScopeList = new ArrayList<>();
                    if (ageScope.getAgeStrList() != null && !ageScope.getAgeStrList().isEmpty()) {
                        ageScopeList.addAll(ageScope.getAgeStrList());
                    } else {
                        for (RuleDto.DayScope dayScope : ruleDto.getAge().getDayScope()) {
                            String age = DateUtil.day2Age(dayScope.getMin()) + "~" + DateUtil.day2Age(dayScope.getMax());
                            ageScopeList.add(age);
                        }
                    }
                    desc = desc + StringUtils.join(ageScopeList, "、") + "]";
                }
            }
            if (ruleDto.getReqPhysician() != null) {
                RuleDto.LimitScope reqPhysicianScope = ruleDto.getReqPhysician();
                if (CollectionUtils.isNotEmpty(reqPhysicianScope.getValue())) {
                    desc += ",申请医生:[";
                    if (StringUtils.isNotBlank(reqPhysicianScope.getGrant())) {
                        desc = desc + turn2Grant(reqPhysicianScope.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(reqPhysicianScope.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getDiagnosticKeyword() != null) {
                RuleDto.LimitScope diagnosticKeyword = ruleDto.getDiagnosticKeyword();
                if (CollectionUtils.isNotEmpty(diagnosticKeyword.getValue())) {
                    desc += ",诊断关键词:[";
                    if (StringUtils.isNotBlank(diagnosticKeyword.getGrant())) {
                        desc = desc + turn2Grant(diagnosticKeyword.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(diagnosticKeyword.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getReqDayScope() != null) {
                RuleDto.NumScope reqDayScope = ruleDto.getReqDayScope();
                desc += ",开单时间:[";
                if (StringUtils.isNotBlank(reqDayScope.getGrant())) {
                    desc = desc + turn2Grant(reqDayScope.getGrant()) + "=>";
                }
                desc = desc + ((reqDayScope.getMin() != null) ? reqDayScope.getMin() : 0) + "~" + ((reqDayScope.getMax() != null) ? reqDayScope.getMax() : 0) + "天前]";
            }
            if (ruleDto.getTerminalType() != null) {
                RuleDto.LimitScope terminalType = ruleDto.getTerminalType();
                if (CollectionUtils.isNotEmpty(terminalType.getValue())) {
                    desc += ",预约渠道:[";
                    if (StringUtils.isNotBlank(terminalType.getGrant())) {
                        desc = desc + turn2Grant(terminalType.getGrant()) + "=>";
                    }
                    desc = desc + StringUtils.join(terminalType.getValue(), "、") + "]";
                }
            }
            if (ruleDto.getGestationalWeek() != null) {
                RuleDto.GestationalWeekScope gestationalWeekScope = ruleDto.getGestationalWeek();
                if (CollectionUtils.isNotEmpty(gestationalWeekScope.getDayScope())) {
                    desc += ",孕周约束:[";
                    if (StringUtils.isNotBlank(gestationalWeekScope.getGrant())) {
                        desc = desc + turn2Grant(gestationalWeekScope.getGrant()) + "=>";
                    }
                    List<String> gestationalWeekScopeList = new ArrayList<>();
                    if (gestationalWeekScope.getGestationalWeekStrList() != null && !gestationalWeekScope.getGestationalWeekStrList().isEmpty()) {
                        gestationalWeekScopeList.addAll(gestationalWeekScope.getGestationalWeekStrList());
                    } else {
                        for (RuleDto.DayScope dayScope : gestationalWeekScope.getDayScope()) {
                            String gestationalWeekStr = DateUtil.day2Age(dayScope.getMin()) + "~" + DateUtil.day2Age((int) dayScope.getMax());
                            gestationalWeekScopeList.add(gestationalWeekStr);
                        }
                    }
                    desc = desc + StringUtils.join(gestationalWeekScopeList, "、") + "]";
                }
            }
        }
        desc += " }";
        return desc;
    }

    private String turn2ExcludeFlag(String excludeFlag) {
        String result = "允许";
        if (StringUtils.isNotBlank(excludeFlag) && "1".equals(excludeFlag)) {
            result = "排斥";
        }
        return result;
    }

    private String turn2Grant(String grant) {
        String result = "";
        switch (grant) {
            case "0": {
                result = "排除";
                break;
            }
            case "1": {
                result = "包含";
                break;
            }
            default: {
                result = "其它";
                break;
            }
        }
        return result;
    }

    @Override
    public JsonResult getExamSysLogList(ExamSyslogDto dto) {
        Page<?> page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        dto.setModuleName(moduleName4String(dto.getModuleName()));

        List<ExamSyslog> list = baseMapper.getExamSysLogList(dto);
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(dto.getPageNo());
        pageVO.setPageSize(dto.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        return JsonResultUtil.success("成功", list, pageVO);
    }

    @Override
    public void saveLog(String moduleName, String operateName, String desc) {
        if (StringUtils.isNotBlank(desc)) {
            ExamSyslogDto examSyslogDto = new ExamSyslogDto();
            examSyslogDto.setModuleName(moduleName);
            examSyslogDto.setOperateName(operateName);
            DictUsersDto usersDto = commonServiceImpl.dictUsers(new ExamApplyDto());
            examSyslogDto.setUserId(usersDto.getUserId());
            examSyslogDto.setUserName(usersDto.getName());
            examSyslogDto.setComputerName(usersDto.getIpAddress());
            examSyslogDto.setOperateDate(DateUtil.getCurrDateStr());
            examSyslogDto.setOperateTime(DateUtil.getCurrentTime());
            if (desc.length() >= 3600) {
                desc = desc.substring(0, 3580) + "......}";
            }
            examSyslogDto.setDescription(desc);
            baseMapper.insert(examSyslogDto);
        }
    }


    @Override
    public void saveQueueDesc(String moduleName, String operateName, DictExamQueue oldQueue, DictExamQueue newQueue) {
        String desc = null;
        if (ConstantsUtil.OperateName.INSERT.getDesc().equals(operateName)) {
            desc = "新增队列：" + newQueue.getQueueName();
        } else if (ConstantsUtil.OperateName.DELETE.getDesc().equals(operateName)) {
            desc = "删除队列：" + newQueue.getQueueName();
        } else {
            if (StringUtils.isNotBlank(newQueue.getUseFlag())) {
                oldQueue.setUseFlag(CommonUtil.convertStopFlag(oldQueue.getUseFlag()));
                newQueue.setUseFlag(CommonUtil.convertStopFlag(newQueue.getUseFlag()));
            }
            String str = LogUtil.compareObject(oldQueue, newQueue);
            if (StringUtils.isNotBlank(str)) {
                desc = "修改队列：" + oldQueue.getQueueName() + "{" + str + "}";
            }
        }
        saveLog(moduleName, operateName, desc);
    }

    @Override
    public void saveItemDesc(String moduleName, String operateName, List<String> descList) {
        String desc = null;
        if (ConstantsUtil.OperateName.UPDATE.getDesc().equals(operateName)) {
            desc = descList.toString();
        }
        saveLog(moduleName, operateName, desc);
    }

    @Override
    public void saveReminderDesc(String moduleName, String operateName, DictCommonUse oldCommonUse, DictCommonUse newCommonUse) {
        String desc = null;
        if (ConstantsUtil.OperateName.INSERT.getDesc().equals(operateName)) {
            desc = "凭条类型：" + newCommonUse.getName() + "，检查类别：" + newCommonUse.getExamClass() + "，预约终端：" + newCommonUse.getReserve1();
            desc = desc + (org.springframework.util.StringUtils.isEmpty(newCommonUse.getSortNo()) ? "" : ("，排序：" + newCommonUse.getSortNo())) + (org.springframework.util.StringUtils.isEmpty(newCommonUse.getValue()) ? "" : ("，提示内容：" + newCommonUse.getValue()));
        } else if (ConstantsUtil.OperateName.DELETE.getDesc().equals(operateName)) {
            desc = "凭条类型：" + newCommonUse.getName() + "，检查类别：" + newCommonUse.getExamClass() + "，提示内容：" + newCommonUse.getValue();
        } else {
            if (StringUtils.isNotBlank(newCommonUse.getReserve1())) {
                oldCommonUse.setReserve1(CommonUtil.convertTerminalType(oldCommonUse.getReserve1()));
                newCommonUse.setReserve1(CommonUtil.convertTerminalType(newCommonUse.getReserve1()));
            }
            if (StringUtils.isNotBlank(newCommonUse.getName())) {
                oldCommonUse.setName(CommonUtil.ReminderType(oldCommonUse.getName()));
                newCommonUse.setName(CommonUtil.ReminderType(newCommonUse.getName()));
            }
            String str = LogUtil.compareObject(oldCommonUse, newCommonUse);
            if (StringUtils.isNotBlank(str)) {
                desc = "修改友情提示：{" + str + "}";
            }
        }
        saveLog(moduleName, operateName, desc);
    }

    private String moduleName4String(String moduleName) {
        String result = null;
        if (StringUtils.isNotBlank(moduleName)) {
            switch (moduleName) {
                case "通用号源": {
                    result = "DICT_SCHEDULE_APM_COMMON";
                    break;
                }
                case "星期号源": {
                    result = "DICT_SCHEDULE_APM_WEEK";
                    break;
                }
                case "日期号源": {
                    result = "DICT_SCHEDULE_APM_DATE";
                    break;
                }
                case "预约规则": {
                    result = "DICT_SCHEDULE_REGULAR_DEF";
                    break;
                }
                case "预约队列": {
                    result = "DICT_SCHEDULE_QUEUE";
                    break;
                }
                case "检查项目": {
                    result = "DICT_EXAM_ITEM";
                    break;
                }
                case "友情提示": {
                    result = "DICT_REMINDER";
                    break;
                }
                case "项目分组": {
                    result = "ITEM_GROUP";
                    break;
                }
            }
        }
        return result;
    }

    private void flagsToItemFlags(List<DictExamItemDto> dictExamItemDtoList) {
        for (DictExamItemDto examItemDto : dictExamItemDtoList) {
            examItemDto.setItemFlags(CommonUtil.flag2itemFlag(examItemDto.getFlags()));
        }
    }
}
